import playNotificationSound from "../utils/playNoticicationSound";
import {
	getGridCode,
	getSurroundingGrids
} from '../utils/getSurroundingGrids'
import store from "../store";


export const sendText = async (toTarget, msgs, storeData) => {
 	if (msgs === '') {
		uni.showToast({
			title: '不能发送空消息'
		});
		return;
	}
	var content = {
		text: msgs
	};
	var messageType = 2;
	const msg = await sendMsg(messageType, toTarget, content, storeData);

	return msg

}

export const voiceMsg = async (toTarget, voiceData, storeData) => {

	var content = {
		voicePath: voiceData.voicePath,
		duration: Math.ceil(voiceData.duration)
	};
	var messageType = 1;
	const msg = await sendMsg(messageType, toTarget, content, storeData);

	return msg

}

export const videoMsg = async (toTarget, item, storeData,text) => {
	try {
		const messageType = 6;
		const content = {
			videoPath: item,
			text:text
		};
		// 假设 sendMsg 是异步函数，使用 await 等待其完成
		const msg = await sendMsg(messageType, toTarget, content, storeData);


		return {data:msg,code:true}
	} catch (e) {
		console.error('发送视频消息时出错:', e);
		return {
			code: false,
			errorMessage: e.message
		};
	}

}

export const mediaMsg = async (toTarget, mediapath, storeData) => {
	const mediaPaths = mediapath.paths.map((item) => ({
		url: item.url,
		fileId: item.fileID
	}))

	const messageType = 3;
	const content = {
		mediaPath: mediaPaths,
		text: mediapath.content
	};
	console.log('content', content);
	try {
		const msg = await sendMsg(messageType, toTarget, content, storeData);
		return msg
	} catch (error) {
		console.error('发送图片消息时出错:', error);
		// 可以在这里进行错误处理，例如提示用户等
	}



}


export async function sendMsg(msgType, Target, content, storeData) {
	const {
		user,
		location,
		senderLocation,
		ws
	} = storeData;

	var msgContent = {
		text: "",
		voicePath: "",
		duration: 0,
		productId: "",
		sendshopId: "",
		mediaPath: "",
		senderLocation: senderLocation
	}
	msgContent = {
		...msgContent,
		...content
	}
	// 构建消息对象
	//webScoketType类型（msg：发送消息）
	const msg = {
		sendUserId: user?.userId,
		userTel: user?.userTel,
		nicPic: user?.nicPic,
		nicName: user?.nicName,
		content: msgContent,
		location: location,
		toTarget: Target,
		messageType: msgType,
		timestamp: Date.now(),
		receiveDistance: 500,
		webSocketType: 'msg',
		isRead: false,
		grid: getGridCode(location)
	};

	try {

		// 检查 WebSocket 连接状态和必要数据是否存在
		console.log("ws",ws);
		if (ws.readyState === 1) {

			ws.send({
				data: JSON.stringify(msg)
			});
			console.log('aaaa',storeData);
			if (storeData.stateConfig.isSound===1) {
				console.log("声音。。。。。。。。");
				playNotificationSound('send');
			}else if(storeData.stateConfig.isSound===2){
				uni.vibrateShort()
			}


			return msg;
		} else {
			console.warn('WebSocket 不可用，消息入队');
			readySendMsg(msg);
			return msg;
		}

	} catch (e) {
		// 捕获并记录错误信息
		console.error('发送消息时出现错误:', e.message);
		return null;
	}
}
export async function productMsg(toTarget, msgs, storeData) {
	var content = {
		productId: msgs,

	};
	var messageType = 4;
	const msg = await sendMsg(messageType, toTarget, content, storeData);

	return msg
}

function readySendMsg(msg) {
	store.commit('msg/SET_messageQueue', msg)

}